﻿using FriendAD.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FriendAD.web.Areas.Member.Controllers
{
    [Authorize]
    public class AdController : Controller
    {
        private AdManager admanage;
        private UserManager usermanage;
        public AdController()
        {
            usermanage = new UserManager();
            admanage = new AdManager();
        }
        // GET: Member/Ad
        public ActionResult Index(string act, int id = -1)
        {
            if  (id!=-1&&act=="del")
            {
                Ad mod = admanage.Find(id);
                mod.isDel = true;
                admanage.Update(mod);
            }
            return View(admanage.getUserAd(User.Identity.Name));
        }

        public ActionResult Add()
        {
            return View(new Ad());
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add(Ad post,HttpPostedFileBase img,HttpPostedFileBase qrcode)
        {
            if (ModelState.IsValid)
            {
                if (img==null)
                {
                    ModelState.AddModelError("Img", "请选择广告图片");
                    return View();
                }
                Core.Types.Response _res = myCommon.saveImg(img);
                Ad mod = new Ad();
                if (_res.Code==0)
                {
                    ModelState.AddModelError("Img", _res.Message);
                    return View();
                }

                mod.Img = _res.Data;

                if (qrcode!=null)
                {
                    var res = myCommon.saveImg(qrcode);
                    if (res.Code==0)
                    {
                        ModelState.AddModelError("qrcode", _res.Message);
                        return View();
                    }
                    mod.Qrcode = res.Data;
                }

                mod.Title = post.Title;
                mod.tell = post.tell;
                mod.Link = post.Link;
                mod.UserId = usermanage.Find(user=>user.UserName== User.Identity.Name).UserID;


               var addres= admanage.Add(mod);
                if (addres.Code!=0)
                {
                    return RedirectToAction("index");
                }
            }
            return View();
        }
    }
}